from google.appengine.api import users
import jinja2, os, webapp2, urllib, cgi, sessions
from datatypes import *

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

def giveError(self, msg):
    template = jinja_environment.get_template('static/generror.html')
    self.response.out.write(template.render({'navbar': navbar(self),
        'error_msg': msg}))

def navbar(RequestHandler):
    navbar_template = jinja_environment.get_template('dynamic/navbar.part.html')
    left_links = [{'url': '/offer/search', 'name': 'Learn Something'}]
    if not sessions.isRegistered():
        links = ['<a href="%s">Sign in or register</a>'
                 % users.create_login_url("/signup")]
    else:
        username = sessions.nameFromUserModel()
        links = ['<a href="/users/myaccount"> {0} </a>'.format(
            cgi.escape(username)),                 
                 '<a href="%s"> Log Out </a>' % users.create_logout_url('/'),
                 '<a href="/communicate/inbox"> Message People </a>']
        left_links += [{'url': '/offer/create', 'name': 'Teach Something'}]
    if sessions.isAdmin():
        links += ['<a href="/adminConsole"> Admin Console </a>']
    return navbar_template.render({'right_links': links,
                                   'left_links': left_links})

#index page
class MainPage(webapp2.RequestHandler):
    def get(self):
        tags = Tag.all().order('numOffers').fetch(10)
        tagLinks = []
        for tag in tags:
            tagLinks.append({'name': tag.tag,
                'url': '/offer/listing?id=' + str(tag.taggedOffers[0])})
        if sessions.isRegistered():
            mainPage_template = jinja_environment.get_template(
                'dynamic/indexRegistered.html')
        else:
            mainPage_template = jinja_environment.get_template(
                'dynamic/indexUnregistered.html')
        self.response.out.write(mainPage_template.render(
            {'navbar': navbar(self),
             'left_links': tagLinks}))

#registration form
class RegForm(webapp2.RequestHandler):
    def get(self):
        if not sessions.isUserLoggedIn():
            self.redirect(users.create_login_url('/signup'))
            return
        if not sessions.isRegistered():
            user = sessions.UserFromSession().nickname()
            signup_form = jinja_environment.get_template('static/signup.html')
            self.response.out.write(signup_form.render({'navbar': navbar(self),
                                                        'userNick': user}))
        else:
            self.redirect('/') #if users are already logged in/signed up, don't show them that page
            return
#about page
class AboutPage(webapp2.RequestHandler):
    def get(self):
        about_template = jinja_environment.get_template('static/about.html')
        self.response.out.write(about_template.render({'navbar': navbar(self)}))

#contact page
class ContactPage(webapp2.RequestHandler):
    def get(self):
        contact_template = jinja_environment.get_template('static/contact.html')
        self.response.out.write(contact_template.render({'navbar': navbar(self)}))

class AdminConsole(webapp2.RequestHandler):
    def get(self):
        console_template = jinja_environment.get_template('static/AdminConsole.html')
        self.response.out.write(console_template.render({'navbar':navbar(self)}) )
        

class Logout(webapp2.RequestHandler):
    def get(self):
        self.redirect(users.create_logout_url('/'))

class NotYetImp(webapp2.RequestHandler):
    def get(self):
        self.response.out.write("Not yet implemented.")
    
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/signup', RegForm),
                               ('/about', AboutPage),
                               ('/contact', ContactPage),
                               ('/logout', Logout),
                               ('/adminConsole', AdminConsole),
                               ('/static/notYetImplemented.html', NotYetImp)
                               ],
                              debug=True,
                              config={'webapp2_extras.sessions':
                                      {'secret_key':'secret password to come'}})
